package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.data.local.entity.GameRecordEntity
import com.hwpt.chesedemo.presentation.theme.strings
import com.hwpt.chesedemo.presentation.viewmodel.EvaluationState
import com.hwpt.chesedemo.presentation.viewmodel.EvaluationViewModel
import com.hwpt.chesedemo.presentation.viewmodel.InputMethod

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EvaluationScreen(
    navController: NavController,
    viewModel: EvaluationViewModel = hiltViewModel()
) {
    val strings = strings()
    val gradient = Brush.verticalGradient(
        colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
    )

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        strings.evaluation,
                        color = Color.White
                    )
                },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = strings.back,
                            tint = Color.White
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(gradient)
                .padding(paddingValues)
        ) {
            EvaluationContent(viewModel)
        }
    }
}

@Composable
fun EvaluationContent(viewModel: EvaluationViewModel) {
    val state = viewModel.state
    val scrollState = rememberScrollState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .padding(16.dp)
    ) {
        // 输入方法选择
        InputMethodSection(
            selectedMethod = state.selectedInputMethod,
            onMethodSelected = viewModel::onInputMethodSelected
        )

        Spacer(modifier = Modifier.height(16.dp))

        when (state.selectedInputMethod) {
            InputMethod.RECORD -> {
                GameRecordsSection(
                    records = state.gameRecords,
                    selectedRecord = state.selectedRecord,
                    onRecordSelected = viewModel::onRecordSelected
                )
            }
            InputMethod.TEXT -> {
                TextInputSection(
                    pgnText = state.pgnText,
                    onTextChanged = viewModel::onPgnTextChanged
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        AnalyzeButton(
            enabled = state.isAnalyzeEnabled,
            isLoading = state.isLoading,
            onAnalyze = viewModel::onAnalyze
        )

        if (state.isLoading) {
            Spacer(modifier = Modifier.height(16.dp))
        }

        if (state.showResults) {
            Spacer(modifier = Modifier.height(24.dp))
            ResultsSection(state)
        }
    }
}

@Composable
fun InputMethodSection(
    selectedMethod: InputMethod,
    onMethodSelected: (InputMethod) -> Unit
) {
    val strings = strings()

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "📊",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Text(
                    text = strings.selectGameData,
                    color = Color.White,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(12.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                MethodButton(
                    text = strings.gameRecordSelection,
                    isSelected = selectedMethod == InputMethod.RECORD,
                    onClick = { onMethodSelected(InputMethod.RECORD) },
                    modifier = Modifier.weight(1f)
                )
                MethodButton(
                    text = strings.pastePgnText,
                    isSelected = selectedMethod == InputMethod.TEXT,
                    onClick = { onMethodSelected(InputMethod.TEXT) },
                    modifier = Modifier.weight(1f)
                )
            }
        }
    }
}

@Composable
fun GameRecordsSection(
    records: List<GameRecordEntity>,
    selectedRecord: GameRecordEntity?,
    onRecordSelected: (GameRecordEntity) -> Unit
) {
    val strings = strings()

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        )
    ) {
        if (records.isEmpty()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = strings.noGameRecords,
                    color = Color.White.copy(alpha = 0.7f),
                    fontSize = 16.sp
                )
            }
        } else {
            LazyColumn(
                modifier = Modifier.height(400.dp)
            ) {
                itemsIndexed(records) { index, record ->
                    GameRecordItem(
                        record = record,
                        isSelected = record.id == selectedRecord?.id,
                        onSelected = { onRecordSelected(record) }
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GameRecordItem(
    record: GameRecordEntity,
    isSelected: Boolean,
    onSelected: () -> Unit
) {
    val strings = strings()

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp, horizontal = 8.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) {
                Color.Black.copy(alpha = 0.3f)
            } else {
                Color.Black.copy(alpha = 0.2f)
            }
        ),
        border = if (isSelected) {
            androidx.compose.foundation.BorderStroke(4.dp, Color.White)
        } else {
            null
        },
        onClick = onSelected
    ) {
        Column(
            modifier = Modifier.padding(18.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = formatDate(record.createdAt),
                    color = Color.White.copy(alpha = 0.8f),
                    fontSize = 14.sp
                )
                Text(
                    text = when (record.result) {
                        "win" -> strings.win
                        "loss" -> strings.loss
                        "draw" -> strings.drawResult
                        else -> record.result
                    },
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(10.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "${strings.aiDifficulty}：${record.aiDifficulty}",
                    color = Color.White,
                    fontSize = 16.sp
                )
            }

            Spacer(modifier = Modifier.height(5.dp))

            Text(
                text = "${strings.roundCount}：${record.moveCount/2}",
                color = Color.White.copy(alpha = 0.8f),
                fontSize = 13.sp
            )
        }
    }
}

@Composable
fun TextInputSection(
    pgnText: String,
    onTextChanged: (String) -> Unit
) {
    val strings = strings()
    var showExample by remember { mutableStateOf(false) }

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            TextField(
                value = pgnText,
                onValueChange = onTextChanged,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(500.dp),
                placeholder = {
                    Text(
                        strings.pastePgnFormat,
                        color = Color.White.copy(alpha = 0.6f)
                    )
                },
                colors = TextFieldDefaults.colors(
                    focusedTextColor = Color.White,
                    unfocusedTextColor = Color.White,
                    focusedContainerColor = Color.Black.copy(alpha = 0.2f),
                    unfocusedContainerColor = Color.Black.copy(alpha = 0.2f),
                    focusedIndicatorColor = Color.White.copy(alpha = 0.5f),
                    unfocusedIndicatorColor = Color.White.copy(alpha = 0.3f),
                    cursorColor = Color.White
                )
            )
        }
    }
}

@Composable
fun AnalyzeButton(
    enabled: Boolean,
    isLoading: Boolean,
    onAnalyze: () -> Unit
) {
    val strings = strings()

    Button(
        onClick = onAnalyze,
        modifier = Modifier
            .fillMaxWidth()
            .height(60.dp),
        enabled = enabled && !isLoading,
        colors = ButtonDefaults.buttonColors(
            containerColor = Color.White.copy(alpha = 0.2f),
            disabledContainerColor = Color.White.copy(alpha = 0.1f)
        ),
        elevation = ButtonDefaults.buttonElevation(
            defaultElevation = 4.dp,
            pressedElevation = 8.dp
        )
    ) {
        if (isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.size(20.dp),
                color = Color.White,
                strokeWidth = 2.dp
            )
            Spacer(modifier = Modifier.size(8.dp))
        }
        Text(
            text = if (isLoading) strings.analyzingDot else strings.startAnalysis,
            color = Color.White,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

@Composable
fun ResultsSection(state: EvaluationState) {
    val strings = strings()

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "📈",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Text(
                    text = strings.analysisResults,
                    color = Color.White,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 玩家对比
            PlayersComparison(state)

            Spacer(modifier = Modifier.height(16.dp))

            // 分析详情
            AnalysisDetails(state)
        }
    }
}

@Composable
fun PlayersComparison(state: EvaluationState) {
    val strings = strings()

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 白方玩家卡片
        PlayerCard(
            playerName = strings.whitePlayer,
            eloRating = state.whiteElo,
            accuracy = state.whiteAccuracy,
            blunders = state.whiteBlunders,
            mistakes = state.whiteMistakes,
            inaccuracies = state.whiteInaccuracies,
            strengthPercentage = 85,
            modifier = Modifier.weight(1f)
        )

        // 黑方玩家卡片
        PlayerCard(
            playerName = strings.blackPlayer,
            eloRating = state.blackElo,
            accuracy = state.blackAccuracy,
            blunders = state.blackBlunders,
            mistakes = state.blackMistakes,
            inaccuracies = state.blackInaccuracies,
            strengthPercentage = 90,
            modifier = Modifier.weight(1f)
        )
    }
}

@Composable
fun PlayerCard(
    playerName: String,
    eloRating: Int,
    accuracy: Int,
    blunders: Int,
    mistakes: Int,
    inaccuracies: Int,
    strengthPercentage: Int,
    modifier: Modifier = Modifier
) {
    val strings = strings()

    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = playerName,
                color = Color.White,
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = eloRating.toString(),
                color = Color.White,
                fontSize = 32.sp,
                fontWeight = FontWeight.Bold
            )

            Text(
                text = strings.eloRating,
                color = Color.White.copy(alpha = 0.8f),
                fontSize = 14.sp
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 实力条
            StrengthMeter(percentage = strengthPercentage)

            Spacer(modifier = Modifier.height(16.dp))

            // 统计数据
            PlayerStats(
                accuracy = accuracy,
                blunders = blunders,
                mistakes = mistakes,
                inaccuracies = inaccuracies
            )
        }
    }
}

@Composable
fun StrengthMeter(percentage: Int) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(10.dp)
            .background(Color.Black.copy(alpha = 0.2f))
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth(percentage / 100f)
                .height(10.dp)
                .background(
                    Brush.horizontalGradient(
                        colors = listOf(
                            Color(0xFFFF6B6B),
                            Color(0xFFFFD93D),
                            Color(0xFF6BCF7F)
                        )
                    )
                )
        )
    }
}

@Composable
fun PlayerStats(
    accuracy: Int,
    blunders: Int,
    mistakes: Int,
    inaccuracies: Int
) {
    val strings = strings()

    val stats = listOf(
        Pair("$accuracy%", strings.accuracy),
        Pair(blunders.toString(), strings.blunders),
        Pair(mistakes.toString(), strings.mistakes),
        Pair(inaccuracies.toString(), strings.inaccuracies)
    )

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        stats.chunked(2).forEach { chunk ->
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                chunk.forEach { (value, label) ->
                    StatItem(value = value, label = label)
                }
            }
        }
    }
}

@Composable
fun StatItem(value: String, label: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.Black.copy(alpha = 0.2f)
        )
    ) {
        Column(
            modifier = Modifier.padding(10.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = value,
                color = Color.White,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
            Text(
                text = label,
                color = Color.White.copy(alpha = 0.8f),
                fontSize = 12.sp
            )
        }
    }
}

@Composable
fun AnalysisDetails(state: EvaluationState) {
    val strings = strings()

    val details = listOf(
        Pair(strings.gameResult, state.gameResult),
        Pair(strings.gameQuality, state.gameQuality)
    )

    Column(
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        details.forEach { (label, value) ->
            DetailItem(label = label, value = value)
        }
    }
}

@Composable
fun DetailItem(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            color = Color.White.copy(alpha = 0.8f),
            fontSize = 14.sp
        )
        Text(
            text = value,
            color = Color.White,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

private fun formatDate(timestamp: Long): String {
    return java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
        .format(java.util.Date(timestamp))
}